//
//  BuyCarViewController.m
//  YaDiuDiu
//
//  Created by 欧洪飞 on 2017/8/23.
//  Copyright © 2017年 jy. All rights reserved.
//

#import "BuyCarViewController.h"

#import "BuyCarCell.h"
#import "DianPuViewController.h"
#import "WashCarViewController.h"
#import "AddCarViewController.h"


#import "AddServiceViewController.h"
#import "AddSUVViewController.h"
#import "SearchViewController.h"
@interface BuyCarViewController ()<UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate,BMKMapViewDelegate,BMKLocationServiceDelegate,BMKGeoCodeSearchDelegate>{
    UILabel *labLine;
    NSMutableArray *datas;//购车数据
    NSMutableArray *array2;//洗车数据
    UIView *headview;
    
    BMKMapView *mapView;
    BMKLocationService *location;
    NSInteger pageNo;//页数
    CGFloat lat;
    CGFloat lng;
}

@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)NSMutableDictionary *dic;

@end

@implementation BuyCarViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [user setObject:@"http://ydd.xtangguo.com/" forKey:@"ImageUrl"];
    //[user setObject:@"19" forKey:@"userid"];
    _dic = [NSMutableDictionary dictionary];
    datas = [NSMutableArray array];
    array2 = [NSMutableArray array];
    [_dic setObject:@"aaa" forKey:@"tag"];
    pageNo = 1;
    
    [self loadNav];
    [self loadUI];
    
    [self loadData];
    [self loadData2];
    
    //定位
    //[self loadMap];
    //[self loadRefresh];
}

- (void)loadMap{
    location = [[BMKLocationService alloc] init];
    [location startUserLocationService];
    
}

-(void)viewWillAppear:(BOOL)animated{
    [mapView viewWillAppear];
    location.delegate = self;
}

-(void)viewWillDisappear:(BOOL)animated{
    [mapView viewWillDisappear];
    location.delegate = nil;
}

#pragma -mark BMKLocationServiceDelegate
-(void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation{
    NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
    lat = userLocation.location.coordinate.latitude;
    lng = userLocation.location.coordinate.longitude;
    [location stopUserLocationService];
    [self loadData];
    [self loadData2];
}

- (void)loadNav{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 64)];
    view.backgroundColor = [UIColor whiteColor];
    view.userInteractionEnabled = YES;
    [self.view addSubview:view];
    
    UILabel *lab = [[UILabel alloc] init];
    lab.text = @"购车";
    lab.textColor = [UIColor blackColor];
    lab.font = [UIFont systemFontOfSize:18.0];
    [view addSubview:lab];
    [lab makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(view.centerX);
        make.top.equalTo(34);
    }];
    
    UILabel *line = [[UILabel alloc] init];
    line.backgroundColor = [UIColor lightGrayColor];
    [view addSubview:line];
    [line makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(0);
        make.right.equalTo(0);
        make.bottom.equalTo(view.bottom);
        make.height.equalTo(0.5);
    }];
    
    //
    UIButton *btnSearch = [UIButton buttonWithType:UIButtonTypeCustom];
    btnSearch.frame = CGRectMake(ScreenWidth-40, 24, 40, 40);
    [btnSearch setImage:[UIImage imageNamed:@"搜索-(1)"] forState:UIControlStateNormal];
    [btnSearch addTarget:self action:@selector(clickSearch) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:btnSearch];
    
}

- (void)clickSearch{
    SearchViewController *search = [[SearchViewController alloc] init];
    [self.navigationController pushViewController:search animated:YES];
}

- (void)loadUI{
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, ScreenWidth, ScreenHeight-64-49) style:UITableViewStylePlain];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    //去掉分割线
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    //自适应高度
//    _tableView.rowHeight = UITableViewAutomaticDimension;
//    _tableView.estimatedRowHeight = 163.0;
    _tableView.rowHeight = 163.0;
    [self.view addSubview:_tableView];
    
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 171)];
    headView.backgroundColor = [UIColor orangeColor];
    _tableView.tableHeaderView = headView;
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 171)];
    imageView.image = [UIImage imageNamed:@"img"];
    [headView addSubview:imageView];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(click)];
    imageView.userInteractionEnabled = YES;
    [imageView addGestureRecognizer:tap];
    
}
//轮播图点击事件
- (void)click{
    
}

#pragma -mark UITableViewDataSource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSString *str = [_dic objectForKey:@"tag"];
    if ([str isEqualToString:@"aaa"]) {
        return datas.count;
    }
    return array2.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *str = [_dic objectForKey:@"tag"];
    
    if ([str isEqualToString:@"aaa"]) {
        static NSString *cellId = @"Cell1";
        BuyCarCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        if (!cell) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"BuyCarCell" owner:nil options:nil] lastObject];
        }
        //取消选中效果
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        NSDictionary *dic = datas[indexPath.row];
        
        NSString *guideprice = [NSString stringWithFormat:@"%@万",[dic objectForKey:@"sellingprice"]];
        
        NSDictionary *attribtDic = @{NSStrikethroughStyleAttributeName: [NSNumber numberWithInteger:NSUnderlineStyleSingle]};
        NSMutableAttributedString *attribtStr = [[NSMutableAttributedString alloc]initWithString:guideprice attributes:attribtDic];
        cell.labPrice1.attributedText = attribtStr;
        
        cell.labName.text = [dic objectForKey:@"name"];
        cell.labStyle.text = [dic objectForKey:@"brand"];
        cell.labPrice2.text = [NSString stringWithFormat:@"%@万",[dic objectForKey:@"guideprice"]];
        //
        NSString *km = [NSString stringWithFormat:@" %likm",[[dic objectForKey:@"km"] integerValue]];
        
        NSString *countcomment = [NSString stringWithFormat:@" %li",[[dic objectForKey:@"countcomment"] integerValue]];
        NSString *thenumberof = [NSString stringWithFormat:@" %li",[[dic objectForKey:@"thenumberof"] integerValue]];
        //        
        NSString *imgUrl = [NSString stringWithFormat:@"%@%@",[user objectForKey:@"ImageUrl"],[dic objectForKey:@"carthemephoto"]];
        
        [cell.images sd_setImageWithURL:[NSURL URLWithString:imgUrl] placeholderImage:[UIImage imageNamed:@"timg-(1)"]];
        
        [cell.btnLeft setTitle:km forState:UIControlStateNormal];
        [cell.btnCenter setTitle:thenumberof forState:UIControlStateNormal];
        [cell.btnRight setTitle:countcomment forState:UIControlStateNormal];
        
        [cell.btnCenter setImage:[UIImage imageNamed:@"浏览"] forState:UIControlStateNormal];
        
        return cell;
    }else{
        static NSString *cellId = @"Cell2";
        BuyCarCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        if (!cell) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"BuyCarCell" owner:nil options:nil] lastObject];
        }
        //取消选中效果
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        NSDictionary *dic = array2[indexPath.row];
        
        cell.labName.text = [dic objectForKey:@"name"];
        cell.labStyle.text = [dic objectForKey:@"carname"];
        //门面价格
        NSString *guideprice = [NSString stringWithFormat:@"%@元",[dic objectForKey:@"limousineprice"]];
        NSDictionary *attribtDic = @{NSStrikethroughStyleAttributeName: [NSNumber numberWithInteger:NSUnderlineStyleSingle]};
        NSMutableAttributedString *attribtStr = [[NSMutableAttributedString alloc]initWithString:guideprice attributes:attribtDic];
        cell.labPrice1.attributedText = attribtStr;
        
        cell.labYDDP.text = @"丢丢价";
        cell.labPrice2.text = [NSString stringWithFormat:@"%@元",[dic objectForKey:@"limousinediudiuprice"]];
        
        NSString *str = [dic objectForKey:@"figurepic"];
        NSString *imgUrl = [NSString stringWithFormat:@"%@%@",[user objectForKey:@"ImageUrl"],str];
        [cell.images sd_setImageWithURL:[NSURL URLWithString:imgUrl] placeholderImage:[UIImage imageNamed:@"timg-(1)"]];
        
        NSString *km = [NSString stringWithFormat:@" %likm",[[dic objectForKey:@"km"] integerValue]];
        NSString *order = [NSString stringWithFormat:@" %li",[[dic objectForKey:@"order"] integerValue]];
        NSString *countcomment = [NSString stringWithFormat:@" %li",[[dic objectForKey:@"countcomment"] integerValue]];
        
        [cell.btnLeft setTitle:km forState:UIControlStateNormal];
        [cell.btnCenter setTitle:order forState:UIControlStateNormal];
        [cell.btnCenter setImage:[UIImage imageNamed:@"订单"] forState:UIControlStateNormal];
        [cell.btnRight setTitle:countcomment forState:UIControlStateNormal];
        return cell;
    }
    
}


//
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    //如果存在就直接返回view
    if (headview)
    {
        return headview;
    }
    headview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 50)];
    headview.backgroundColor = [UIColor whiteColor];
    
    NSArray *array = @[@"购车",@"洗车",@"上户",@"车险"];
    for (NSInteger i=0; i<array.count; i++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(ScreenWidth/array.count*i, 0, ScreenWidth/array.count, 50);
        [btn setTitle:array[i] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        btn.tag = i;
        [headview addSubview:btn];
        [btn addTarget:self action:@selector(clicks:) forControlEvents:UIControlEventTouchUpInside];
        
        UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(ScreenWidth/4*(i+1), 15, 1, 20)];
        lab.backgroundColor = [UIColor lightGrayColor];
        [headview addSubview:lab];
        
    }
    
    labLine = [[UILabel alloc] initWithFrame:CGRectMake((ScreenWidth/4-40)/2, 45, 40, 5)];
    labLine.backgroundColor = [UIColor redColor];
    [headview addSubview:labLine];
    
    return headview;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 50.0;
}

//按钮点击事件
- (void)clicks:(UIButton *)btn{
    if (btn.tag == 0) {
        [_dic setObject:@"aaa" forKey:@"tag"];
        [UIView animateWithDuration:0.3 animations:^{
            labLine.frame = CGRectMake((ScreenWidth/4-40)/2, 45, 40, 5);
        }];

        [_tableView reloadData];
    }else if (btn.tag == 1){
        [_dic setObject:@"sss" forKey:@"tag"];
        [UIView animateWithDuration:0.3 animations:^{
            labLine.frame = CGRectMake((ScreenWidth/4-40)/2+(ScreenWidth/4), 45, 40, 5);
        }];
        
        [_tableView reloadData];
    }else if (btn.tag == 2){
        [_dic setObject:@"ddd" forKey:@"tag"];
        [UIView animateWithDuration:0.3 animations:^{
            labLine.frame = CGRectMake((ScreenWidth/4-40)/2+(ScreenWidth/4)*2, 45, 40, 5);
        }];
        
        [_tableView reloadData];
    }else{
        [_dic setObject:@"fff" forKey:@"tag"];
        [UIView animateWithDuration:0.3 animations:^{
            labLine.frame = CGRectMake((ScreenWidth/4-40)/2+(ScreenWidth/4)*3, 45, 40, 5);
        }];
        
        [_tableView reloadData];
    }
    
}
//点击cell事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *str = [_dic objectForKey:@"tag"];
    NSString *longitude = [NSString stringWithFormat:@"%f",lng];
    NSString *latitude = [NSString stringWithFormat:@"%f",lat];
    
    if ([str isEqualToString:@"aaa"]) {
        //属性传值
        NSDictionary *dic = datas[indexPath.row];
        NSString *carid = [dic objectForKey:@"id"];
        NSString *name = [dic objectForKey:@"name"];
        NSString *place = [dic objectForKey:@"suite"];
        NSString *llcount = [NSString stringWithFormat:@"%li",[[dic objectForKey:@"countcomment"] integerValue]];
        NSString *start = [NSString stringWithFormat:@"%li",[[dic objectForKey:@"star"] integerValue]];
        NSString *km = [NSString stringWithFormat:@"%likm",[[dic objectForKey:@"km"] integerValue]];
        
        DianPuViewController *det = [[DianPuViewController alloc] init];
        det.CarId = carid;
        det.name = name;
        det.place = place;
        det.count = llcount;
        det.start = start;
        det.km = km;
        det.lat = latitude;
        det.lng = longitude;
        [self.navigationController pushViewController:det animated:YES];
    }else{
        //属性传值
        NSDictionary *op = array2[indexPath.row];
        NSString *carid2 = [op objectForKey:@"id"];
        NSString *name2 = [op objectForKey:@"name"];
        NSString *place2 = [op objectForKey:@"suite"];
        NSString *llcount2 = [NSString stringWithFormat:@"%li",[[op objectForKey:@"countcomment"] integerValue]];
        NSString *start2 = [NSString stringWithFormat:@"%li",[[op objectForKey:@"star"] integerValue]];
        NSString *km2 = [NSString stringWithFormat:@"%likm",[[op objectForKey:@"km"] integerValue]];
        
        WashCarViewController *car = [[WashCarViewController alloc] init];
        car.carId = carid2;
        car.name = name2;
        car.place = place2;
        car.count = llcount2;
        car.start = start2;
        car.km = km2;
        car.lat = latitude;
        car.lng = longitude;
        [self.navigationController pushViewController:car animated:YES];
    }
}
//
- (void)loadRefresh{
    //下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
    //
    [self.tableView.mj_header beginRefreshing];
    //根据位置设置半透明
    self.tableView.mj_header.automaticallyChangeAlpha = YES;
    //上拉加载更多
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    
}

- (void)loadTag{
    NSString *tag = [_dic objectForKey:@"tag"];
    if ([tag isEqualToString:@"aaa"]) {
        
    }else{
        
    }
}

- (void)loadMoreData{
    [_tableView.mj_header endRefreshing];
    pageNo++;
    NSMutableDictionary *parmas = [NSMutableDictionary dictionary];
    NSString *longitude = [NSString stringWithFormat:@"%f",lng];
    NSString *latitude = [NSString stringWithFormat:@"%f",lat];
    [parmas setObject:longitude forKey:@"longitude"];
    [parmas setObject:latitude forKey:@"latitude"];
    [parmas setObject:[NSString stringWithFormat:@"%li",pageNo] forKey:@"p"];
    NSString *url = [NSString stringWithFormat:@"%@/App/CarBuying/index",urlHead];
    [[AFHTTPSessionManager manager] POST:url parameters:parmas success:^(NSURLSessionDataTask *task, id responseObject) {
        NSArray *arr = [responseObject objectForKey:@"result"];
        NSLog(@"arrcount:%li",arr.count);
        
        [_tableView.mj_footer endRefreshing];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [_tableView.mj_footer endRefreshing];
    }];
    
}

//购车店铺列表
- (void)loadData{
    [SVProgressHUD show];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
    
    NSMutableDictionary *parmas = [NSMutableDictionary dictionary];
    NSString *longitude = [NSString stringWithFormat:@"%f",lng];
    NSString *latitude = [NSString stringWithFormat:@"%f",lat];
    [parmas setObject:longitude forKey:@"longitude"];
    [parmas setObject:latitude forKey:@"latitude"];
    [parmas setObject:@"1" forKey:@"p"];
    NSLog(@"parmas:%@",parmas);
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString *url = [NSString stringWithFormat:@"%@/App/CarBuying/index",urlHead];
    [manager POST:url parameters:parmas success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"购车店铺列表res:%@",responseObject);
        datas = [responseObject objectForKey:@"result"];
        [_tableView reloadData];
        
        [SVProgressHUD dismiss];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"error:%@",error);
        [SVProgressHUD dismiss];
    }];
    
}
//洗车店铺列表
- (void)loadData2{
    NSMutableDictionary *parmas = [NSMutableDictionary dictionary];
    NSString *longitude = [NSString stringWithFormat:@"%f",lng];
    NSString *latitude = [NSString stringWithFormat:@"%f",lat];
    [parmas setObject:longitude forKey:@"longitude"];
    [parmas setObject:latitude forKey:@"latitude"];
    [parmas setObject:@"1" forKey:@"p"];
    NSLog(@"parmas:%@",parmas);
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString *url = [NSString stringWithFormat:@"%@/App/CarWash/index",urlHead];
    [manager POST:url parameters:parmas success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"洗车店铺列表res:%@",responseObject);
        array2 = [responseObject objectForKey:@"result"];
        [_tableView reloadData];
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"error:%@",error);
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
